package com.wxxymaker.hook;

import com.blade.ioc.annotation.Inject;
import com.blade.mvc.hook.Signature;
import com.blade.mvc.hook.WebHook;
import com.blade.mvc.http.Request;
import com.blade.mvc.http.Response;
import com.wxxymaker.hook.annotation.AdminIgnore;
import com.wxxymaker.hook.annotation.AdminRequire;
import com.wxxymaker.model.entity.Admin;
import com.wxxymaker.service.AdminService;
import com.wxxymaker.utils.Base64Util;
import com.wxxymaker.utils.Const;

/**
 * @Author: Soft
 * @Date: 2018/6/2 21:42
 * @Desc: 管理员登录验证拦截器
 */
public class AdminHook implements WebHook {
    @Inject
    private AdminService service;

    @Override
    public boolean before(Signature signature) {
        AdminRequire require = signature.getRoute().getTargetType().getAnnotation(AdminRequire.class);
        AdminIgnore  ignore  = signature.getRoute().getAction().getAnnotation(AdminIgnore.class);

        Response response = signature.response();
        Request  request  = signature.request();

        if (require != null && ignore == null) {
            if (auth(request, response)) {
                return true;
            }
        } else {
            return true;
        }

        String url = request.url();
        response.redirect("/admin/login?prev=" + Base64Util.encode(url));
        return false;
    }

    private boolean auth(Request request, Response response) {
        Admin admin = request.session().attribute(Const.SessionKey);
        if (admin == null) {
            admin = Admin.toAdmin(request.cookie(Const.CookieKey));
        }
        if (admin != null) {
            Admin check = service.check(admin.getName(), admin.getPass());
            if (check != null) {
                request.attribute("admin", check); // 将管理员信息放到request域中
                return true;
            }
        }
        return false;
    }
}
